#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

int main()
{
    try
    {
        sql::Driver  *driver;
        sql::Connection *con;
        sql::PreparedStatement *prep_stmt;
        // sql::Statement *stmt;
        sql::ResultSet *res;

        // 创建 MySQL 驱动实例
        driver = get_driver_instance();

        // 建立连接
        con = driver->connect("tcp://127.0.0.1:3306", "root", "Ff2291123610");

        // 选择数据库
        con->setSchema("test");

        // 创建语句对象
        // stmt = con->createStatement();
        prep_stmt = con->prepareStatement("INSERT INTO user(username, password) VALUES (?, ?)");
        prep_stmt->setString(1, "1");
        prep_stmt->setString(2, "a");
        // prep_stmt->executeQuery(); // 查询语句使用
        prep_stmt->executeUpdate(); //用于执行不返回数据的SQL语句，如 INSERT、UPDATE、DELETE 以及DDL语句（如 CREATE TABLE、DROP TABLE）。

        // pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC");
        // res = pstmt->executeQuery();
        // while (res->next()) {
        //     // You can use either numeric offsets...
        //     cout << "id = " << res->getInt(1); // getInt(1) returns the first column
        //     // ... or column names for accessing results.
        //     // The latter is recommended.
        //     cout << ", label = '" << res->getString("label") << "'" << endl;
        // }
        // res->afterLast();
        // while (res->previous())
        //     cout << "\t... MySQL counts: " << res->getInt("id") << endl;
        // prep_stmt->execute();
        // 执行查询
        // res = stmt->executeQuery("INSERT INTO user(username, password) VALUES (1, 'a')");

        // // 处理结果集
        // while (res->next())
        // {
        //     std::cout << "\t... MySQL replies: " << res->getString("_message") << std::endl;
        // }

        // 清理
        delete res;
        // delete stmt;
        delete prep_stmt;
        delete con;
    }
    catch (sql::SQLException &e)
    {
        std::cerr << "# ERR: SQLException in " << __FILE__;
        std::cerr << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl;
        std::cerr << "# ERR: " << e.what();
        std::cerr << " (MySQL error code: " << e.getErrorCode();
        std::cerr << ", SQLState: " << e.getSQLState() << " )" << std::endl;
    }

    return 0;
}